package com.wisemoresystem.seal.base.plugin.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ne.framework.data.util.ChkTools;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wisemoresystem.seal.base.action.ProjBaseAction;
import com.wisemoresystem.seal.base.tip.Tip;
import com.wisemoresystem.seal.util.cookie.CookieTools;
import com.wisemoresystem.seal.util.json.JsonTools;

public class TipInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse resp,
			Object arg2, ModelAndView arg3) throws Exception {
		if (arg2.getClass() == HandlerMethod.class) {
			HandlerMethod hm = (HandlerMethod) arg2;
			ProjBaseAction baseAction = (ProjBaseAction) hm.getBean();

			String tipJson = JsonTools.toJson(baseAction.tip);
			// System.err.println("post--->" + tipJson);
			CookieTools.setAttribute("tip", tipJson, resp);
		}

	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,
			Object arg2) throws Exception {
		if (arg2.getClass() == HandlerMethod.class) {
			HandlerMethod hm = (HandlerMethod) arg2;
			ProjBaseAction baseAction = (ProjBaseAction) hm.getBean();

			String tipJson = CookieTools.getAttribute("tip", req);
			// System.err.println("pre-->" + tipJson);
			if (ChkTools.isNotNull(tipJson)) {
				Tip tip = (Tip) JsonTools.jsonStrToJsonObject(tipJson,
						baseAction.tip.getClass());
				if (tip != null && ChkTools.isNotNull(tip.getMsg())) {
					baseAction.tip = tip;
				} else {
					baseAction.tip = new Tip();
				}
			} else {
				baseAction.tip = new Tip();
			}
		}

		return true;
	}
}
